<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>股票财务数据分析系统</title>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .input-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }
        input, select, button {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            box-sizing: border-box;
        }

        input[type="number"] {
            -moz-appearance: textfield;
        }

        input[type="number"]::-webkit-outer-spin-button,
        input[type="number"]::-webkit-inner-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            cursor: pointer;
            font-weight: bold;
            margin-top: 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        .button-group {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin: 20px 0;
        }

        .btn {
            padding: 10px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s ease;
            min-width: 120px;
        }

        .btn-primary {
            background: #007bff;
            color: white;
        }

        .btn-primary:hover {
            background: #0056b3;
            transform: translateY(-1px);
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #1e7e34;
            transform: translateY(-1px);
        }

        .btn-info {
            background: #17a2b8;
            color: white;
        }

        .btn-info:hover {
            background: #117a8b;
            transform: translateY(-1px);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #545b62;
            transform: translateY(-1px);
        }
        #chart {
            width: 100%;
            height: 500px;
            margin-top: 20px;
        }
        .loading {
            text-align: center;
            color: #666;
            font-style: italic;
        }
        .error {
            color: #dc3545;
            background: #f8d7da;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
        .success {
            color: #155724;
            background: #d4edda;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .data-table th, .data-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        .data-table th {
            background-color: #f2f2f2;
        }
        .stock-quick {
            color: #007bff;
            cursor: pointer;
            text-decoration: underline;
        }
        .stock-quick:hover {
            color: #0056b3;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>📈 股票财务数据分析系统</h1>
        <div style="text-align: center; margin-bottom: 20px; color: #666;">
            <p>✅ 测试一：股票财务数据分析 | 🔄 支持动态查询 | 📊 实时图表展示</p>
        </div>
        
        <div class="input-section">
            <h3>数据获取与查询</h3>
            
            <div class="form-group">
                <label for="stockCode">股票代码:</label>
                <input type="text" id="stockCode" placeholder="例如: 000001" value="000001">
                <div style="margin-top: 8px;">
                    <small style="color: #666;">常用代码:
                        <span class="stock-quick" onclick="setStock('000001')">000001(平安银行)</span> |
                        <span class="stock-quick" onclick="setStock('000002')">000002(万科A)</span> |
                        <span class="stock-quick" onclick="setStock('600519')">600519(贵州茅台)</span> |
                        <span class="stock-quick" onclick="setStock('300920')">300920(润阳科技)</span> |
                        <span class="stock-quick" onclick="setStock('002415')">002415(海康威视)</span>
                    </small>
                </div>
            </div>
            
            <div class="button-group">
                <button onclick="fetchStockData()" class="btn btn-primary">📊 获取数据</button>
                <button onclick="showChart()" class="btn btn-success">📈 显示图表</button>
                <button onclick="queryData()" class="btn btn-info">🔍 条件查询</button>
                <button onclick="clearAll()" class="btn btn-secondary">🗑️ 清空</button>
            </div>
            
            <div class="form-group" style="margin-top: 20px;">
                <label>查询条件 (可选):</label>
                <div style="display: flex; gap: 10px;">
                    <input type="number" id="startYear" placeholder="开始年份" min="2015" max="2030" style="flex: 1; width: auto;">
                    <input type="number" id="endYear" placeholder="结束年份" min="2015" max="2030" style="flex: 1; width: auto;">
                </div>
                <small style="color: #666; margin-top: 5px; display: block;">
                    💡 <strong>按钮说明：</strong>
                    📊获取数据=显示表格 | 📈显示图表=生成可视化图表 | 🔍条件查询=按年份筛选数据
                </small>
            </div>
        </div>
        
        <div id="message"></div>
        <div id="chart"></div>
        <div id="dataTable"></div>

        <div style="margin-top: 40px; padding: 20px; background: #f8f9fa; border-radius: 8px;">
            <h3>💡 系统说明</h3>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <h4>🎯 主要功能</h4>
                    <ul>
                        <li>📊 获取股票近6年财务数据</li>
                        <li>🔍 SQL动态查询与筛选</li>
                        <li>📈 Plotly交互式图表</li>
                        <li>💾 SQLite数据库存储</li>
                    </ul>
                </div>
                <div>
                    <h4>🔧 技术栈</h4>
                    <ul>
                        <li>后端：FastAPI + SQLAlchemy</li>
                        <li>前端：HTML + JavaScript + Plotly</li>
                        <li>数据库：SQLite</li>
                        <li>数据源：akshare (演示模式)</li>
                    </ul>
                </div>
            </div>
            <p style="margin-top: 15px; color: #666; font-size: 14px;">
                📝 当前为演示模式，使用模拟数据。实际部署时可连接akshare获取真实股票数据。
            </p>
        </div>
    </div>

    <script>
        // 快速设置股票代码
        function setStock(code) {
            document.getElementById('stockCode').value = code;
        }

        // 清空所有内容
        function clearAll() {
            // 清空输入框
            document.getElementById('stockCode').value = '';
            document.getElementById('startYear').value = '';
            document.getElementById('endYear').value = '';

            // 清空显示区域
            document.getElementById('message').innerHTML = '';
            document.getElementById('chart').innerHTML = '';
            document.getElementById('dataTable').innerHTML = '';

            showMessage('已清空所有内容', 'success');
        }

        // 显示消息
        function showMessage(message, type = 'info') {
            const messageDiv = document.getElementById('message');
            messageDiv.innerHTML = `<div class="${type}">${message}</div>`;
            setTimeout(() => {
                messageDiv.innerHTML = '';
            }, 5000);
        }

        // 获取股票财务数据
        async function fetchStockData() {
            const stockCode = document.getElementById('stockCode').value;
            if (!stockCode) {
                showMessage('请输入股票代码', 'error');
                return;
            }

            showMessage('正在获取数据...', 'loading');
            
            try {
                const response = await fetch(`/api/stock/financial/${stockCode}`);
                const data = await response.json();
                
                if (response.ok) {
                    showMessage(`成功获取 ${data.stock_name}(${data.stock_code}) 的财务数据`, 'success');
                    displayDataTable(data.data, data.stock_name, data.stock_code);
                } else {
                    showMessage(data.detail || '获取数据失败', 'error');
                }
            } catch (error) {
                showMessage('网络错误: ' + error.message, 'error');
            }
        }

        // 显示图表
        async function showChart() {
            const stockCode = document.getElementById('stockCode').value;
            const startYear = document.getElementById('startYear').value;
            const endYear = document.getElementById('endYear').value;

            if (!stockCode) {
                showMessage('请输入股票代码', 'error');
                return;
            }

            showMessage('正在生成图表...', 'loading');

            try {
                // 构建查询参数，包含年份范围
                let queryParams = new URLSearchParams();
                if (startYear) queryParams.append('start_year', startYear);
                if (endYear) queryParams.append('end_year', endYear);

                const url = `/api/stock/chart/${stockCode}${queryParams.toString() ? '?' + queryParams.toString() : ''}`;
                const response = await fetch(url);
                const data = await response.json();

                if (response.ok) {
                    Plotly.newPlot('chart', data.chart_data.data, data.chart_data.layout);
                    const yearRange = startYear && endYear ? ` (${startYear}-${endYear})` : '';
                    showMessage(`已生成 ${data.stock_info.name}${yearRange} 的财务图表`, 'success');
                } else {
                    showMessage(data.detail || '生成图表失败', 'error');
                }
            } catch (error) {
                showMessage('网络错误: ' + error.message, 'error');
            }
        }

        // 查询数据
        async function queryData() {
            const stockCode = document.getElementById('stockCode').value;
            const startYear = document.getElementById('startYear').value;
            const endYear = document.getElementById('endYear').value;
            
            let queryParams = new URLSearchParams();
            if (stockCode) queryParams.append('stock_code', stockCode);
            if (startYear) queryParams.append('start_year', startYear);
            if (endYear) queryParams.append('end_year', endYear);
            
            showMessage('正在查询数据...', 'loading');
            
            try {
                const response = await fetch(`/api/stock/query?${queryParams}`);
                const result = await response.json();
                
                if (response.ok) {
                    showMessage(`查询到 ${result.count} 条记录`, 'success');
                    displayQueryResults(result.data);
                } else {
                    showMessage(result.detail || '查询失败', 'error');
                }
            } catch (error) {
                showMessage('网络错误: ' + error.message, 'error');
            }
        }

        // 显示数据表格
        function displayDataTable(data, stockName, stockCode) {
            const tableDiv = document.getElementById('dataTable');
            
            if (!data || data.length === 0) {
                tableDiv.innerHTML = '<p>暂无数据</p>';
                return;
            }
            
            let html = `<h3>${stockName}(${stockCode}) 财务数据</h3>`;
            html += '<table class="data-table">';
            html += '<tr><th>年份</th><th>营业收入</th><th>净利润</th><th>报告日期</th></tr>';
            
            data.forEach(item => {
                html += `<tr>
                    <td>${item.year}</td>
                    <td>${(item.revenue / 100000000).toFixed(2)} 亿</td>
                    <td>${(item.net_profit / 100000000).toFixed(2)} 亿</td>
                    <td>${item.report_date}</td>
                </tr>`;
            });
            
            html += '</table>';
            tableDiv.innerHTML = html;
        }

        // 显示查询结果
        function displayQueryResults(data) {
            const tableDiv = document.getElementById('dataTable');
            
            if (!data || data.length === 0) {
                tableDiv.innerHTML = '<p>暂无数据</p>';
                return;
            }
            
            let html = '<h3>查询结果</h3>';
            html += '<table class="data-table">';
            html += '<tr><th>股票代码</th><th>股票名称</th><th>年份</th><th>营业收入</th><th>净利润</th></tr>';
            
            data.forEach(item => {
                html += `<tr>
                    <td>${item.stock_code}</td>
                    <td>${item.stock_name}</td>
                    <td>${item.year}</td>
                    <td>${(item.revenue / 100000000).toFixed(2)} 亿</td>
                    <td>${(item.net_profit / 100000000).toFixed(2)} 亿</td>
                </tr>`;
            });
            
            html += '</table>';
            tableDiv.innerHTML = html;
        }
    </script>
</body>
</html>
